﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using ODS.Config;
using ODS.Utils;
using System.IO;
using ODS.Model;
using System.Windows;

namespace ODS.WebService.DeviceFunctions
{
    public class RetrievesDeviceDigestListService
    {
        static bool IsAuthenticated = true;

        public static async Task<InfoResult> RetrievesDeviceDigestList()
        {
            String url = Constants.SERVER_URL + "/devices/digest";

            InfoResult result;
            try
            {
                Stream xmlStream = await RESTfulService.HTTPGetRequest(url);

                List<DeviceModel> resultString = ParseXML(xmlStream);

                #region check authenticate
                if (!IsAuthenticated)
                {
                    InfoResult result_login = await Login_Logout.LoginService.loginService(App.userLogin.UserLoginName, App.userLogin.UserPassword);
                    if (result_login.IsSuccess)
                    {
                        if ((String)result_login.ReturnedObject == Constants.SUCCESS)
                        {
                            IsAuthenticated = true;

                            return await RetrievesDeviceDigestList();
                        }
                        else
                        {
                            MessageBox.Show((String)result_login.ReturnedObject);
                            App.BackToLoginPage();

                        }
                    }
                    else
                    {
                        MessageBox.Show(result_login.Error);
                        App.BackToLoginPage();

                    }


                }
                #endregion

                result = new InfoResult(null, resultString);
            }
            catch (Exception ex)
            {
                result = new InfoResult(ex.Message, null);
            }
            return result;
        }

        private static List<DeviceModel> ParseXML(Stream xmlStream)
        {
            List<DeviceModel> listDeviceModel = new List<DeviceModel>();
            XDocument doc = XDocument.Load(xmlStream);

            var Authenticate = (from authen in doc.Descendants("unauthorized")
                                select new
                                {

                                }).FirstOrDefault();
            if (Authenticate != null)
            {
                IsAuthenticated = false;
                return null;
            }

            var devices = from device in doc.Descendants("deviceDigest")
                          select new
                          {
                              DeviceDetails = from DeviceDetail in device.Descendants("deviceDetails")
                                              select new
                                              {
                                                  ExpiresAt = DeviceDetail.Element("expiresAt").Value,
                                                  IMEI = DeviceDetail.Element("imei").Value,
                                                  MSISDN = DeviceDetail.Element("msisdn").Value,
                                                  Name = DeviceDetail.Element("name").Value,
                                                  Requests = DeviceDetail.Element("requests").Value,

                                              },

                              EventDegits = from EventDegit in device.Descendants("eventDigest")
                                              select new
                                              {
                                                  LastAt = EventDegit.Element("lastAt").Value,
                                                  Unread = EventDegit.Element("unread").Value,

                                              },

                              LatestMessages = from LatestMessage in device.Descendants("latestMessage")
                                           select new
                                           {
                                               GeneratedAt = LatestMessage.Element("generatedAt").Value,
                                               Heading = LatestMessage.Element("heading").Value,
                                               Ignition = LatestMessage.Element("ignition").Value,
                                               Latitude = LatestMessage.Element("latitude").Value,
                                               Longitude = LatestMessage.Element("longitude").Value,
                                               Odometer = LatestMessage.Element("odometer").Value,
                                               ReceivedAt = LatestMessage.Element("receivedAt").Value,
                                               Speed = LatestMessage.Element("speed").Value,

                                           },
                              

                          };

            if (devices != null)
            {
                foreach (var device in devices)
                {
                    DeviceModel deviceModel = new DeviceModel();

                    if (device.DeviceDetails !=null && device.DeviceDetails.Count() > 0)
                    {
                        deviceModel.ExpiresAt = CommonUtil.ParseDateTimeFromString(device.DeviceDetails.FirstOrDefault().ExpiresAt);
                        deviceModel.DeviceIMEI = device.DeviceDetails.FirstOrDefault().IMEI;
                        deviceModel.DevicePhoneNumber = device.DeviceDetails.FirstOrDefault().MSISDN;
                        deviceModel.VehicleName = device.DeviceDetails.FirstOrDefault().Name;
                        deviceModel.RemainingRequestNumber = device.DeviceDetails.FirstOrDefault().Requests;
                    }

                    if (device.EventDegits != null && device.EventDegits.Count() > 0)
                    {
                        
                        deviceModel.LastAt = CommonUtil.ParseDateTimeFromString(device.EventDegits.FirstOrDefault().LastAt);
                        deviceModel.UnreadNumber = device.EventDegits.FirstOrDefault().Unread;
                    }

                    if (device.LatestMessages != null && device.LatestMessages.Count() > 0)
                    {
                        deviceModel.LastMessage = new MessageModel();
                        deviceModel.LastMessage.GeneratedAt = CommonUtil.ParseDateTimeFromString(device.LatestMessages.FirstOrDefault().GeneratedAt);
                        deviceModel.LastMessage.Heading = device.LatestMessages.FirstOrDefault().Heading;
                        deviceModel.LastMessage.Ignition = device.LatestMessages.FirstOrDefault().Ignition;
                        deviceModel.LastMessage.Latitude = device.LatestMessages.FirstOrDefault().Latitude;
                        deviceModel.LastMessage.Longitude = device.LatestMessages.FirstOrDefault().Longitude;
                        deviceModel.LastMessage.Odometer = device.LatestMessages.FirstOrDefault().Odometer;
                        deviceModel.LastMessage.ReceivedAt = CommonUtil.ParseDateTimeFromString(device.LatestMessages.FirstOrDefault().ReceivedAt);
                        deviceModel.LastMessage.Speed = device.LatestMessages.FirstOrDefault().Speed;
                    }


                    listDeviceModel.Add(deviceModel);
                }
            }


            return listDeviceModel;
        }
    }
}
